package com.zhao.dota.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhao.dota.struct.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权限访问时触发
 */
@Component
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException {
        Result<String> error = Result.error(String.format("请求[%s]被拒绝", httpServletRequest.getRequestURI()));
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        String text = objectMapper.writeValueAsString(error);
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.getWriter().write(text);
    }
}
